package br.com.gaspar.tm.bo;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Stateless;

import org.primefaces.model.UploadedFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import br.com.gaspar.framework.modelo.BaseBO;
import br.com.gaspar.framework.persistencia.IBaseDAO;
import br.com.gaspar.tm.bo.iface.IBlogBO;
import br.com.gaspar.tm.dao.iface.IProjetoDAO;
import br.com.gaspar.tm.entidade.Blog;
import br.com.gaspar.utils.exception.BaseException;

import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.transfer.TransferManager;

@Stateless
@Local(IBlogBO.class)
public class BlogBO extends BaseBO<Blog> implements IBlogBO {
	
	private static final Logger log = LoggerFactory.getLogger(BlogBO.class);
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 9037085151626072330L;
	
	@EJB
	private IProjetoDAO<Blog> dao;
	
	@Override
	public IBaseDAO<Blog> getDAOPadrao() {
		return this.dao;
	}
	
	@Override
	protected void gravarAntes(Blog entidade) throws BaseException {
		entidade.setDataCriacao(new Date());
	}
	
	@Override
	public void enviarAmazonS3(List<UploadedFile> imagens) throws BaseException {
		String balde = "tmtransporte";
        String pasta = "blog/";
        String caminhoS3 = null;
        InputStream streamImagem = null;
        
        AWSCredentials awsCred = new BasicAWSCredentials("AKIAI6RU2AXQZSMEF3FQ", "J2ULKQ+RFOlnygz0gbQ4UCctr5R1lxUU6Z563fPa");
        //AmazonS3 s3 = new AmazonS3Client(awsCred);
        //List<Bucket> buckets = s3.listBuckets();
        TransferManager tm = new TransferManager(awsCred);   
        
        for (UploadedFile imagem : imagens) {
			caminhoS3 = pasta + imagem.getFileName();
			ObjectMetadata om = new ObjectMetadata();
			om.setContentType(imagem.getContentType());
			// TransferManager processes all transfers asynchronously, 
	        // so this call will return immediately.
	        try {
	        	streamImagem = imagem.getInputstream();
	        	
				tm.upload(balde, caminhoS3, streamImagem, om);
				// Or you can block and wait for the upload to finish
	        } catch (AmazonServiceException e) {
				log.error("AmazonServiceException", e);
			} catch (AmazonClientException e) {
				log.error("AmazonClientException", e);
			} catch (IOException e) {
				log.error("IOException", e);
			}  
        }
	}
}
